package com.huikeportal.controller;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.huikeportal.controller.common.Lang;
import com.huikeportal.controller.common.MessageManager;
import com.huikeportal.model.Language;
import com.huikeportal.model.MessageCommon;
import com.huikeportal.model.RegionType;
import com.huikeportal.model.SiteAllInfo;
import com.huikeportal.model.SiteDataManagerInfo;
import com.huikeportal.model.UserInfo;
import com.huikeportal.model.UserManagerInfo;
import com.huikeportal.model.WordBook;
import com.huikeportal.model.common.PageDataVo;
import com.huikeportal.model.common.SqlParameter;
import com.huikeportal.service.LoginService;
import com.huikeportal.service.SelectSiteService;
import com.huikeportal.service.SiteService;

/**
 * 店铺基础数据管理
 * 
 * @author focus
 * 
 */
@Controller
@Scope("prototype")
public class SiteController {

	@Autowired
	private HttpSession session;
	
	@Autowired
	private SiteService siteService;
	
	@Autowired
	private LoginService loginService;
	
	@Autowired
	private SelectSiteService selectSiteService;
	
	@InitBinder("siteDataManagerInfo")
	public void initBinder(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("siteDataManagerInfo.");
	}

	@InitBinder("pageDataVo")
	public void initBinderPage(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("pageDataVo.");
	}

	@RequestMapping("/siteManager")
	public String siteManager(SiteDataManagerInfo siteDataManagerInfo,
			PageDataVo pageDataVo, ModelMap model) throws Exception {
		
		// 获取登录用户的信息，用来过滤该用户可以看到的Site数据
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		userInfo = loginService.getUserInfo(userInfo);
		siteDataManagerInfo.setUserId(userInfo.getUserId());
		String menuHtml = loginService.getMenuHtml(userInfo, "siteManager");
		
		// 按钮权限
		String sysLang = session.getAttribute("sysLang").toString();
		SqlParameter sql = new SqlParameter();
		sql.setSysLang(sysLang);
		sql.setString("siteManager");
		Integer menuId = selectSiteService.getMenuId(sql);
		List<WordBook> menuList = loginService.getUserButtonList(sysLang, userInfo.getUserId(), menuId);
		String author = "";
		for(int i=0,len=menuList.size();i<len;i++){
			author+=menuList.get(i).getDicValue();
		}
		
		
		// 获取用户权限下的所有广场
		List<SiteAllInfo> squareList = getAllGcList(userInfo);
		
		model.addAttribute("menuHtml", menuHtml);// 左侧菜单html
		model.addAttribute("squareList",squareList);
		
		Language lang = Lang.getInfo("zh_cn");
		model.addAttribute("lang", lang);
		model.addAttribute("author",author);
		model.addAttribute("datetime",siteService.getDate());
		return "siteManager";
	}
	
	
	@ResponseBody
	@RequestMapping("/ajaxSiteList")
	public Map<String, Object> ajaxSiteList(String provinceId, String cityId,String areaId,String square,
			String floor,String siteName, String currentPage) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		SiteDataManagerInfo siteDataManagerInfo = new SiteDataManagerInfo();
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		
		String permitSitesStr = getAllPermitSitesStr(userInfo);
		siteDataManagerInfo.setSiteArea(permitSitesStr);
		
		siteDataManagerInfo.setSquare(square);
		siteDataManagerInfo.setFloor(floor);
		siteDataManagerInfo.setSiteName(URLDecoder.decode(siteName, "UTF-8"));
		siteDataManagerInfo.setSource(MessageManager.getMsg("selectSource"));
		
		// 获取用户信息
		userInfo = loginService.getUserInfo(userInfo);
		// 获取当前系统语言
		String sysLang = session.getAttribute("sysLang").toString();
		// 获取用户语言包
		Language language = Lang.getInfo(sysLang);
		// 查询当前页面id
		SqlParameter sql = new SqlParameter();
		sql.setSysLang(sysLang);
		sql.setString("siteManager");
		Integer menuId = selectSiteService.getMenuId(sql);
		// 获取用户权限按钮信息
		List<WordBook> buttonList = loginService.getUserButtonList(sysLang,
				userInfo.getUserId(), menuId);
		// 按钮过滤
		language = filterLanguage(language, buttonList);
		PageDataVo pageDataVo = new PageDataVo();
		// 默认显示第一页
		if (currentPage == null || "".equals(currentPage)) {
			pageDataVo.setCurrentPage(1);
		} else {
			pageDataVo.setCurrentPage(Integer.parseInt(currentPage));
		}
		// 获取每页显示条数
		pageDataVo.setPageSize(Integer.parseInt(MessageManager
				.getMsg("pageSize")));
		// 设置开始显示条数
		pageDataVo.setStartRow((pageDataVo.getCurrentPage() - 1)
				* pageDataVo.getPageSize());
		// 设置参数
		pageDataVo.setSearchParameter(siteDataManagerInfo);
		// 获取当前页用户信息
		pageDataVo = siteService.getSiteDataList(pageDataVo);
		map.put("language", language);// 系统语言包
		map.put("siteList", pageDataVo.getPageResult());// 结果集
		map.put("currentPage", pageDataVo.getCurrentPage());// 当前页
		map.put("maxPage", pageDataVo.getMaxPage());// 最大页
		map.put("recentUserName", userInfo.getUserName());// 当前登录用户名
		map.put("isDelete", language.getDelete());// 是否有删除权限
		return map;
	}
	
	
	/**
	 * 按钮过滤
	 * 
	 * @param language
	 *            语言包
	 * @param buttonList
	 *            按钮权限
	 * @return
	 * @throws Exception
	 */
	private Language filterLanguage(Language language, List<WordBook> buttonList)
			throws Exception {
		boolean add = false;
		boolean modify = false;
		boolean delete = false;
		for (int i = 0; i < buttonList.size(); i++) {
			if ("2".equals(buttonList.get(i).getDicCode())) {
				add = true;
			}
			if ("3".equals(buttonList.get(i).getDicCode())) {
				modify = true;
			}
			if ("4".equals(buttonList.get(i).getDicCode())) {
				delete = true;
			}
		}
		if (!add) {
			language.setAdd("");
		}
		if (!modify) {
			language.setModify("");
		}
		if (!delete) {
			language.setDelete("");
		}
		return language;
	}
	
	
	private List<SiteAllInfo>  getOriPermissionList(UserInfo userInfo) throws Exception{
		// lowPermission < 300 的是广场以上的权限
		return siteService.getSitesByUser(userInfo);
	}
	
	private int getHighPermission(List<SiteAllInfo> oriList) throws Exception{
		return siteService.getLowPermission(oriList);
	}
	
	private List<SiteAllInfo> getAllGcList(UserInfo userInfo) throws Exception{
		List<SiteAllInfo> list;
		List<SiteAllInfo> oriList = getOriPermissionList(userInfo);
		list = getHighPermission(oriList) <= 300 ? siteService.getAllGcList(oriList) : new ArrayList<SiteAllInfo>();
		return list;
	}
	
	// 获取该用户所拥有的所有的店铺权限
	private String getAllPermitSitesStr(UserInfo userInfo) throws Exception{
		String permitSitesStr = "";
		
		// lowPermission < 300 的是广场以上的权限
		List<SiteAllInfo> permitSiteList = siteService.getSitesByUser(userInfo);
		List<SiteAllInfo> allSiteList = new ArrayList<SiteAllInfo>();
		int lowPermission = siteService.getLowPermission(permitSiteList);
		if(lowPermission < 300){
			List<SiteAllInfo> allGcList = siteService.getAllGcList(permitSiteList);
			allSiteList = siteService.getAllSiteList(allGcList);
			allSiteList.addAll(allGcList);
		}else if(lowPermission > 500){
			allSiteList = permitSiteList;
		}else{
			allSiteList = siteService.getAllSiteList(permitSiteList);
		}
		permitSitesStr = siteService.getSitePermitAreaStr(allSiteList);
		return permitSitesStr;
	}
	
	/**
	 * 修改店铺基础数据
	 * 
	 * @param SiteDataManagerInfo
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/updateSiteData")
	public String updateSiteData(SiteDataManagerInfo siteDataManagerInfo,String siteId,String netArea,String staffNum, ModelMap model)
			throws Exception {
		siteDataManagerInfo.setSiteId(siteId);
		siteDataManagerInfo.setNetArea(Float.parseFloat(netArea));
		siteDataManagerInfo.setStaffNo(Short.parseShort(staffNum));
		MessageCommon messageCommon = siteService.updateSiteData(siteDataManagerInfo);
		
		// 获取登录用户的信息，用来过滤该用户可以看到的Site数据
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		userInfo = loginService.getUserInfo(userInfo);
		String menuHtml = loginService.getMenuHtml(userInfo, "siteManager");
		
		if (!messageCommon.isFlag()) {
			return "error";
		}
		// 返回一览

		PageDataVo pageDataVo = new PageDataVo();
		// 如果是初始化，默认显示第一页
		if (pageDataVo.getCurrentPage() == 0) {
			pageDataVo.setCurrentPage(1);
		}
		
		
		siteDataManagerInfo = new SiteDataManagerInfo();
		siteDataManagerInfo.setUserId(userInfo.getUserId());
		
		// 获取每页显示条数
		pageDataVo.setPageSize(Integer.parseInt(MessageManager
				.getMsg("pageSize")));
		// 设置开始显示条数
		pageDataVo.setStartRow((pageDataVo.getCurrentPage() - 1)
				* pageDataVo.getPageSize());
		pageDataVo.setSearchParameter(siteDataManagerInfo);
		// 获取当前页用户信息
		pageDataVo = siteService.getSiteDataList(pageDataVo);
		model.addAttribute("pageDataVo", pageDataVo);// 用户列表分页信息
		model.addAttribute("siteDataManagerInfo",siteDataManagerInfo);
		model.addAttribute("menuHtml", menuHtml);// 左侧菜单html
		
		Language lang = Lang.getInfo("zh_cn");
		model.addAttribute("lang", lang);
		model.addAttribute("datetime",siteService.getDate());
		return "siteManager";
	
	}
	
	
	
	/**
	 * 根据siteId查询site信息
	 * 
	 * @param String siteId
	 * @return si
	 * @throws Exception
	 */
	@RequestMapping("/queryBySiteId")
	public String queryBySiteId(String siteId, ModelMap model) throws Exception{
		SiteDataManagerInfo siteDataManagerInfo = siteService.queryBySiteId(siteId);
		model.addAttribute("siteDataManagerInfo", siteDataManagerInfo);
		
		Language lang = Lang.getInfo("zh_cn");
		model.addAttribute("lang", lang);
		return "siteDetail";
		
	}
	
	/**
	 * 获取楼层
	 * 
	 * @param String 广场Id
	 * @return Map 所有楼层
	 * @throws Exception
	 */
	@RequestMapping("/getFloors")
	public  @ResponseBody Map getFloors(String squareId) throws Exception{
		   Map jsonMap = new HashMap();
		   List<RegionType> floorList = siteService.getFloors(squareId);
		   List list=new ArrayList(); 
		   if(floorList.size()>0){
			   for(RegionType regionType:floorList)
				   {
				    Map regionMap=new HashMap();
				    regionMap.put("regionId", regionType.getRegionId());
				    regionMap.put("regionName", regionType.getRegionName());
				    list.add(regionMap);
				   }
			   }
		   jsonMap.put("child_region",list);
		   return jsonMap;
		
	}
	
	/**
	 * 获取所有省份
	 * 
	 * @param String 国别ID
	 * @return Map 所有省份
	 * @throws Exception
	 */
	@RequestMapping("/getProvinces")
	public  @ResponseBody Map getProviences(String countryId) throws Exception{
		   Map jsonMap = new HashMap();
		   List<RegionType> provienceList = siteService.getProvinces(countryId);
		   List list=new ArrayList(); 
		   if(provienceList.size()>0){
			   for(RegionType regionType:provienceList)
				   {
				    Map regionMap=new HashMap();
				    regionMap.put("regionId", regionType.getRegionId());
				    regionMap.put("regionName", regionType.getRegionName());
				    list.add(regionMap);
				   }
			   }
		   else{
			    Map regionMap=new HashMap();
			    regionMap.put("regionId", 0);
			    regionMap.put("regionName", null);
			    list.add(regionMap);
		   }
		   jsonMap.put("child_region",list);
		   return jsonMap;
		
	}
	
	/**
	 * 获取所有城市
	 * 
	 * @param String 省份ID
	 * @return Map 所有城市
	 * @throws Exception
	 */
	@RequestMapping("/getCitys")
	public  @ResponseBody Map getCitys(String provinceId) throws Exception{
		   Map jsonMap = new HashMap();
		   List<RegionType> cityList = siteService.getCitys(provinceId);
		   List list=new ArrayList(); 
		   if(cityList.size()>0){
			   for(RegionType regionType:cityList)
				   {
				    Map regionMap=new HashMap();
				    regionMap.put("regionId", regionType.getRegionId());
				    regionMap.put("regionName", regionType.getRegionName());
				    list.add(regionMap);
				   }
			   }
		   else{
			    Map regionMap=new HashMap();
			    regionMap.put("regionId", 0);
			    regionMap.put("regionName", null);
			    list.add(regionMap);
		   }
		   jsonMap.put("child_region",list);
		   return jsonMap;
		
	}
	
	/**
	 * 获取所有地方
	 * 
	 * @param String 城市ID
	 * @param Map 所有地方
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getAreas")
	public  @ResponseBody Map getAreas(String cityId) throws Exception{
		   Map jsonMap = new HashMap();
		   List<RegionType> areaList = siteService.getAreas(cityId);
		   List list=new ArrayList(); 
		   if(areaList.size()>0){
			   for(RegionType regionType:areaList)
				   {
				    Map regionMap=new HashMap();
				    regionMap.put("regionId", regionType.getRegionId());
				    regionMap.put("regionName", regionType.getRegionName());
				    list.add(regionMap);
				   }
			   }
		   else{
			    Map regionMap=new HashMap();
			    regionMap.put("regionId", 0);
			    regionMap.put("regionName", null);
			    list.add(regionMap);
		   }
		   jsonMap.put("child_region",list);
		   return jsonMap;
		
	}
	
	
	/**
	 * 获取所有省份
	 * 
	 * @param String 国别ID
	 * @return Map 所有省份
	 * @throws Exception
	 */
	@RequestMapping("/getSquares")
	public  @ResponseBody Map getSquares(String provinceId,String cityId,String areaId) throws Exception{
		   // 获取登录用户的信息，用来过滤该用户可以看到的Site数据
		   UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		   userInfo = loginService.getUserInfo(userInfo);
		   Map jsonMap = new HashMap();
		   // 获取用户权限下的所有广场
		   List<SiteAllInfo> squareList = getAllGcList(userInfo);
		   List<RegionType> resultList = siteService.filterSquare(provinceId, cityId, areaId, squareList);
		   List list=new ArrayList(); 
		   if(resultList.size()>0){
			   for(RegionType regionType:resultList)
				   {
				    Map regionMap=new HashMap();
				    regionMap.put("regionId", regionType.getRegionId());
				    regionMap.put("regionName", regionType.getRegionName());
				    list.add(regionMap);
				   }
			   }
		   jsonMap.put("child_region",list);
		   return jsonMap;
		
	}
}
